import { ListStore } from '@/store';
import { message } from '@/utils/util';
import {
  INITIAL_FORM_QUERY_VALUE,
  LIST_NAME,
  LOAD_STORE_SETTINGS_LIST_REQUEST_TASK_NAME,
  INITIAL_FORM_STORE_VALUE,
} from '@/views/store-settings/constants';
import { getChinaRegionUrlApi } from '@/views/cellular-area-config/api';
import { loadListStore, loadListCellular, listArea, deleteYfStoreApi } from './api';
import { export_json_to_excel, formatJson } from '@/utils/vendor/Export2Excel';
import { Notification } from 'element-ui';
import { REGION_CITY_STORAGE_KEY } from '@/constants';
import { errorHandler, setLocalStorageByExpire, getLocalStorageByExpire } from '@/utils';

export default class Store extends ListStore {
  formQueryValue = { ...INITIAL_FORM_QUERY_VALUE };

  querying = false;

  visible = false;

  // 删除中
  deleting = false;

  // 当前编辑商品参数 - 用于每次打开Modal时作为其表单初始值传入
  storeFormValue = { ...INITIAL_FORM_STORE_VALUE };

  importVisible = false;

  exporting = false;

  //蜂窝集合
  cellularList = [];

  //片区集合
  areaList = [];

  //片区map
  areaMap = new Map();

  //蜂窝map
  cellularMap = new Map();

  cityList = []; // 省市区列表

  // 加载省市列表
  loadRegionCitys = async () => {
    const storageData = getLocalStorageByExpire(REGION_CITY_STORAGE_KEY);
    if (storageData && Object.prototype.toString.call(storageData) === '[object Array]' && storageData.length > 0) {
      this.cityList = storageData;
      return;
    }

    try {
      const result = (await getChinaRegionUrlApi()) || [];
      const citys = result.map(item => {
        return {
          label: item.region_name,
          value: item.region_name,
          children:
            item.children?.map(childItem => {
              return {
                label: childItem.region_name,
                value: childItem.region_name,
                children:
                  childItem.children?.map(childChildItem => {
                    return {
                      label: childChildItem.region_name,
                      value: childChildItem.region_name,
                      children: undefined,
                    };
                  }) || undefined,
              };
            }) || undefined,
        };
      });

      if (citys.length > 0) {
        // 设置7天有效期
        setLocalStorageByExpire(REGION_CITY_STORAGE_KEY, citys);
        this.cityList = citys;
      } else {
        this.cityList = [];
      }
    } catch (error) {
      errorHandler({ error, showErrorNotification: false });
      this.cityList = [];
    }
  };

  // 加载列表
  loadStoreList = async ({ loadAction = 'reset', pageSize: inputPageSize, pageNum: inputPageNum } = {}) => {
    await this.loadList({
      requestTaskName: LOAD_STORE_SETTINGS_LIST_REQUEST_TASK_NAME,
      listName: LIST_NAME,
      loadAction,
      pageSize: inputPageSize,
      pageNum: inputPageNum,
      loadDataFunc: async ({ pageSize, pageNum }) => {
        const result = await loadListStore(this.formQueryValue, { pageSize, pageNum });
        let { rows: data = [], total = 0 } = result || {};
        data = data.map(item => ({
          ...item,
          cellularName: this.cellularMap.get(item.cellularCode)?.cellularName,
          districtName: this.areaMap.get(item.districtCode),
          storeTypeName: item.storeType === 'KEY_STORES' ? '重点门店' : '非重点门店',
        }));
        return { data, total };
      },
    });
  };
  // 查询门店设置
  queryStoreSettings = value => {
    this.formQueryValue = value;
    this.loadStoreList({ loadAction: 'pageNumChange', pageNum: 1 });
  };

  // 当前页变更
  pageNumChange = pageNum => {
    this.loadStoreList({ loadAction: 'pageNumChange', pageNum });
  };

  // 每页条数变更
  pageSizeChange = pageSize => {
    this.loadStoreList({ loadAction: 'pageSizeChange', pageSize });
  };

  resetTable = () => {
    this.loadStoreList({ loadAction: 'reset' });
  };
  //关闭新增编辑对话框
  onClose = () => {
    this.visible = false;
    this.storeFormValue = { ...INITIAL_FORM_STORE_VALUE };
  };
  //打开新增编辑对话框
  onOpenEditModal = value => {
    this.visible = true;
    if (value) {
      this.storeFormValue = value;
    }
  };
  // 删除益丰门店
  onDelete = async value => {
    const { channelCode } = value;
    try {
      this.deleting = true;
      const res = await deleteYfStoreApi(channelCode);
      if (!res) {
        Notification({ title: '提示', type: 'suceess', message: '删除成功' });
        this.deleting = false;
        this.resetTable();
      }
    } catch (error) {
      this.deleting = false;
      errorHandler({ error });
    }
  };
  //打开导入对话框
  onOpenImportModal = () => {
    this.importVisible = true;
  };
  //关闭导入对话框
  onCloseImport = () => {
    this.importVisible = false;
  };

  listCellular = async () => {
    try {
      this.cellularList = await loadListCellular();
      if (this.cellularList.length > 0) {
        this.cellularList.forEach(item => {
          this.cellularMap.set(item.cellularCode, item);
        });
      }
    } catch (e) {
      message('提示', '获取蜂窝列表异常', 'error');
    }
  };
  listArea = async () => {
    try {
      this.areaList = await listArea();
      if (this.areaList.length > 0) {
        this.areaList.forEach(item => {
          this.areaMap.set(item.areaCode, item.areaName);
        });
      }
    } catch (e) {
      message('提示', '获取片区列表异常', 'error');
    }
  };
  // 初始加载数据
  init = async () => {
    await this.loadRegionCitys();
    await this.listArea();
    await this.listCellular();
    await this.loadStoreList({ loadAction: 'reset' });
  };
  // 导出门店信息
  exportChannelStores = async () => {
    try {
      console.log(this.formQueryValue);
      this.exporting = true;
      const total = this.list.table.total;
      const result = await loadListStore(this.formQueryValue, { pageSize: total, pageNum: 1, countSql: false });
      const list = result.rows;
      if (list && list.length > 0) {
        const tHeader = ['门店名称', '门店编码', '渠道编码', '所在城市', '门店地址', '所属蜂窝', '蜂窝编码', '店型', '城市运营经理'];
        const filterVal = [
          'channelName',
          'storeCode',
          'channelCode',
          'city',
          'address',
          'cellularName',
          'cellularCode',
          'storeLevel',
          'operationManager',
        ];
        list.forEach(item => {
          item.cellularName = this.cellularMap.get(item.cellularCode)?.cellularName;
          item.districtName = this.areaMap.get(item.districtCode);
          item.storeTypeName = item.storeType === 'KEY_STORES' ? '重点门店' : '非重点门店';
        });
        const data = formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '门店信息');
      } else {
        Notification({
          title: '提示',
          message: `没有可导出的数据`,
          type: 'warning',
        });
      }
      this.exporting = false;
    } catch (e) {
      this.exporting = false;
      Notification({
        title: '提示',
        message: `导出列表异常`,
        type: 'error',
      });
    }
  };
}
